package com.chenwut.threadDemo.exercise_7;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.Callable;

/**
 * @author ChenPi
 * @since 2024/09/20 09:09
 */
public class MyCallable implements Callable<int[]> {

    //{10,5,20,50,100,200,500,800,2,80,300,70}
    static ArrayList<Integer> list = new ArrayList<>();

    static {

        Collections.addAll(list, 10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300, 70);
    }


    @Override
    public int[] call() throws InterruptedException {
        ArrayList<Integer> boxList = new ArrayList<>();
        while (true) {
            synchronized (MyCallable.class) {
                if (list.size() == 0) {
                    if (boxList.size() != 0) {
                        int max = Collections.max(boxList);
                        int sum = boxList.stream().mapToInt(Integer::intValue).sum();
                        System.out.println("本次抽奖中 " + Thread.currentThread().getName() + " 产生了 " + boxList.size() + " 个奖项，分别为：" + boxList + "最大奖项为：" + max + " 总和为：" + sum);
                    } else {
                        System.out.println(Thread.currentThread().getName() + "没有产生奖项");
                    }
                    break;
                 }
                if (list.size() > 0) {
                    // 打乱集合
                    Collections.shuffle(list);
                    int prize = list.remove(0);
                    boxList.add(prize);
                }
            }

            // 写在锁里面，线程不会释放锁，其他线程无法获得锁处于等待状态
            // 写到锁外面，此时已经释放了锁，当前线程会睡眠，不参与竞争，其他线程可以获得锁，继续竞争
            Thread.sleep(10);

        }

        if (boxList.size() == 0) {
            return null;
        }
        return new int[]{Collections.max(boxList), boxList.stream().mapToInt(Integer::intValue).sum()};
    }
}
